// 创建 Redux Store
function createStore(reducer) {
  //声明变量, 用来存储状态的值
  let state = undefined;
  //用来保存订阅的回调
  const subscribers = [];

  // 获取当前状态
  function getState() {
    return state;
  }

  // 分发动作        {}
  function dispatch(action) {
    if(typeof action === 'object'){
      state = reducer(state, action);
      // 通知所有订阅者状态已更新
      subscribers.forEach((subscriber) => subscriber());
    }
    if(typeof action === 'function'){
      //调用该函数
      action(dispatch);
    }
  }

  // 订阅状态更新
  function subscribe(subscriber) {
    subscribers.push(subscriber);

    // 返回一个取消订阅的函数
    return function unsubscribe() {
      const index = subscribers.indexOf(subscriber);
      if (index !== -1) {
        subscribers.splice(index, 1);
      }
    };
  }

  // 初始化状态
  dispatch({}); // 触发一次 reducer，获取初始状态

  return {
    getState,
    dispatch,
    subscribe,
  };
}

// 示例 reducer
function counterReducer(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

// 创建 Redux Store
const store = createStore(counterReducer);

// 订阅状态更新
const unsubscribe = store.subscribe(
  () => {
    console.log("当前状态:", store.getState());
  }
);

// 分发动作
store.dispatch({ type: "INCREMENT" }); // 输出: 当前状态: 1
store.dispatch({ type: "INCREMENT" }); // 输出: 当前状态: 2

// 取消订阅
unsubscribe();

store.dispatch({ type: "DECREMENT" }); // 无输出，因为已取消订阅
